<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/6/20
 * Time: 14:42
 */

namespace Biz\module\Classes;

use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\service\BrandUser as sBrandUser;
use Biz\service\SkuInfo;
use Biz\model\trade\Cart as mCart;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Log as tLog;


class ShopCoupon extends Coupon
{


    public static function shopExclusiveList($uid, $shopId, $limit=0)
    {

        $where = [
            'shop_id' => $shopId,
            'coupon_code'=>'',
            'type_time'    => mCouponConfig::TYPE_TIME_STATIC,
            'stop_time[>]' => date('Y-m-d H:i:s'),
            'status'       => mCouponConfig::STATUS_CAN_RECEIVE,
            'total_count[>]'=>\Medoo\Medoo::raw('received_count'),
            'ORDER' => ['coupon_id' => 'DESC'],
        ];

        if($limit>0){
            $where['LIMIT'] = $limit;
        }

        $list = mCouponConfig::select("*", $where);

        //查询此列表中，我已经领取的coupon
        $couponIds = array_column($list, 'coupon_id');

        $mineList = [];

        if ($uid > 0) {
            $mineList = mCouponRecord::select('*', ['uid' => $uid, 'coupon_id' => $couponIds]);
            $mineList = array_column($mineList, null, 'coupon_id');
        }


        $list = array_map(function ($v) use ($mineList) {

            $data = self::formatConfigCoupon($v);

            self::showFormatCoupon($data, $v, 'receive_list');

            $data['is_receive'] = 0;

            if (!empty($mineList[$v['coupon_id']])) {
                $data['is_receive'] = 1;
            }

            return $data;
        }, $list);


        return $list;
    }

    public static function goodsList($couponId,$sortType=0,$areaCode=0,$page = 1){

        $result = ['list' => [], 'is_over' => 0];

        $couponInfo = mCouponConfig::getCouponInfo($couponId,['shop_id','assume','goods_range','include_goods_ids']);

        if(empty($couponInfo)){
            return $result;
        }

        if($couponInfo['assume'] != mCouponConfig::COUPON_ASSUME_SHOP){
            return $result;
        }


        if($couponInfo['goods_range'] == mCouponConfig::GOODS_RANGE_PART){

            $goodsIds = explode(',',$couponInfo['include_goods_ids']);

            $result = sBrandUser::getAllGoods($couponInfo['shop_id'], $goodsIds, $areaCode, $sortType, HhzClient::getClientVersion(), $page);


            return $result;


        }elseif($couponInfo['goods_range'] == mCouponConfig::GOODS_RANGE_ALL){

            $result = sBrandUser::getAllGoods($couponInfo['shop_id'], '', $areaCode, $sortType, HhzClient::getClientVersion(), $page);

        }

        return $result;
    }


    //给出最值得店铺优惠券
    public static function getBestShopCouponSelect($uid,$shopId, $skuBuyList = [])
    {
        $couponSelect = self::calCanUseCouponList($uid, $skuBuyList,0,$shopId);

        if (empty($couponSelect[self::TAB_1])) {
            return [];
        }

        $couponSelect = array_shift($couponSelect[self::TAB_1]);

        if (!empty($couponSelect)) {
            return $couponSelect;
        }
    }

    //在购物车列表页可以选择已领取的优惠券
    public static function shopSelectList($uid, $tabId, $shopId, $skuToken='',$couponId=0,$skuBuyList=[])
    {

        if (empty($skuToken) && empty($skuBuyList)) {
            return [];
        }

        if (!empty($skuToken)) {
            $skuBuyList = self::getSkuBuyListWithOrderSkuToken($uid, $skuToken,$shopId);
        }


        $result = self::calCanUseCouponList($uid, $skuBuyList, $couponId, $shopId);

        return isset($result[$tabId])?$result[$tabId]:[];

    }

    //订单使用优惠券，订单创建成功之前调用
    //return    true  使用成功
    //return    false  使用失败
    public static function useAShopCouponInOrder($uid, $shopId,$orderNo, $sCouponVId, $sCouponId)
    {

        $result = mCouponRecord::update(['use_time' => date('Y-m-d H:i:s'), 'use_order_no' => $orderNo, 'status' => mCouponRecord::COUPON_STATUS_USED], [
            'uid'          => $uid,
            'shop_id'      => $shopId,
            'coupon_vid'   => $sCouponVId,
            'coupon_id'    => $sCouponId,
            'status'       => mCouponRecord::COUPON_STATUS_UNUSED,
            'use_order_no' => ''
        ]);

        if (is_object($result)) {

            if ($result->rowCount() > 0) {

                //优惠券使用次数减少
                mCouponConfig::update(['used_count[+]'=>1],['coupon_id'=>$sCouponId]);

                tLog::coupon_useshopcoupon_info('店铺优惠券使用成功', [
                    'uid'        => $uid,
                    'shop_id'    => $shopId,
                    'order_no'   => $orderNo,
                    'coupon_vid' => $sCouponVId,
                    'coupon_id'  => $sCouponId
                ]);

                return true;
            }
        }

        tLog::coupon_useshopcoupon_warning('店铺优惠券使用失败', [
            'uid'        => $uid,
            'shop_id'    => $shopId,
            'order_no'   => $orderNo,
            'coupon_vid' => $sCouponVId,
            'coupon_id'  => $sCouponId
        ]);

        return false;

    }
    //订单取消，退优惠券
    //return    true  退成功
    //return    false 退失败
    public static function cancelAShopCouponInOrder($uid, $shopId,$orderNo, $sCouponId,$sCouponVId)
    {
        $result = mCouponRecord::update(['use_time' => '0000-00-00 00:00:00', 'use_order_no' => '', 'status' => mCouponRecord::COUPON_STATUS_UNUSED], [
            'uid'          => $uid,
            'shop_id'      => $shopId,
            'coupon_vid'   => $sCouponVId,
            'use_order_no' => $orderNo,
            'status'       => mCouponRecord::COUPON_STATUS_USED,
        ]);

        if (is_object($result)) {

            if ($result->rowCount() > 0) {

                //优惠券使用次数减少
                mCouponConfig::update(['used_count[-]'=>1],['coupon_id'=>$sCouponId]);

                tLog::coupon_cancelshopcoupon_info('订单取消店铺优惠券成功', ['uid' => $uid, 'coupon_vid' => $sCouponVId, 'use_order_no' => $orderNo]);

                return true;
            }
        }

        tLog::coupon_cancelshopcoupo_info('订单取消店铺优惠券失败', ['uid' => $uid, 'coupon_vid' => $sCouponVId, 'use_order_no' => $orderNo]);

        return false;
    }

    //给出一个店铺级别的coupon_id计算订单是否可用该优惠券，如果可用则返回coupon信息，其中包括优惠金额
    public static function giveShopCouponIdCalCanUse($uid, $shopId,$couponId=0, $skuBuyList = [])
    {

        $select = self::shopSelectList($uid, self::TAB_1, $shopId, [],$couponId, $skuBuyList);

        $coupon = array_shift($select);

        return $coupon;
    }

    public static function checkShopHasCoupon($shopId){
        $list = self::shopExclusiveList(0,$shopId,1);

        if(!empty($list)){
            return 1;
        }else{
            return 0;
        }
    }
}